package com.lynn.springboot_demo.utils;


import org.apache.commons.imaging.ImageInfo;
import org.apache.commons.imaging.ImageReadException;
import org.apache.commons.imaging.Imaging;
import java.awt.*;
import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;


/**
 * @author cl
 * @Date 2021/12/20 14:55
 * 获取图片的dpi值的工具类
 */
public class ImgCheckUtil {
    //获取dpi 25.4毫米(mm)
    public static Integer getImageDpiByFile(File file) {
        ImageInfo imageInfo = null;
        int i = 0;
        try {
            imageInfo = Imaging.getImageInfo(file);
            Dimension imageSize = Imaging.getImageSize(file);
            System.out.println(imageSize);
            double sqrt = Math.sqrt(Math.pow(imageSize.width, 2) + Math.pow(imageSize.height, 2));
            BigDecimal b = new BigDecimal(sqrt);
            //斜边等效像素
            double f1 = b.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
            double v = f1 / 25.4;
            BigDecimal b1 = new BigDecimal(v);
            double f2 = b1.setScale(3, BigDecimal.ROUND_HALF_UP).doubleValue();
            System.out.println("斜边等效像素:" + f1);
            System.out.println(f2);
            //图片尺寸
            double width = imageSize.width / f1;
            double height = imageSize.height / f1;
            System.out.println(width);
            System.out.println(height);
            //    显示区域斜边尺寸
            double sqrt1 = Math.sqrt(Math.pow(width, 2) + Math.pow(height, 2));
            System.out.println("显示区域斜边尺寸:" + sqrt1);
            //    DPI
            double v1 = f1 / sqrt1;
            System.out.println(v1);
            long round = Math.round(v1);
            i = Integer.parseInt(String.valueOf(round));
        } catch (ImageReadException | IOException e) {
            e.printStackTrace();
        }
        return i;
    }


    //获取变量的数据类型
    private static String getType(Object a) {
        return a.getClass().toString();

    }


    public static void main(String[] args) {
        File file = new File("C:\\Users\\Administrator\\Desktop\\测试图片\\liantiao_shuzi_sucai-007.jpg");
        Integer imageDpiByFile = getImageDpiByFile(file);
        System.out.println(imageDpiByFile);
    }
}
